package se.webbzon.oschi01.nbt;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Iterator;

import se.webbzon.oschi01.singleton.Singleton;

public class ListTagFactory extends AbstractTagFactory<Iterable<Tag<?>>> implements Singleton {
	
	private ListTagFactory() {
		super(Tags.TAG_LIST, "TAG_List");
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override public Tag<Iterable<Tag<?>>> readTag(String tagName, DataInputStream is) throws IOException {
		byte tagId = is.readByte();
		int size = is.readInt();
		ListTag tag = new ListTag(this, tagName);
		TagFactory factory = AbstractNBTReader.factories.get(tagId);
		for (int i = 0; i < size; i++) {
			tag.addTag(factory.readTag("", is));
		}
		Tag t = tag;
		return t;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override public void writeTag(Tag<Iterable<Tag<?>>> tag, DataOutputStream dos) throws IOException {
		Iterable<Tag<?>> children = tag.getValue();
		Iterator<Tag<?>> it = children.iterator();
		if (it.hasNext()) {
			Tag<?> child = it.next();
			dos.writeByte(child.getFactory().getId());
			dos.writeInt(tag.getChildren().siblings());
			TagFactory factory = child.getFactory();
			factory.writeTag(child, dos);
			while (it.hasNext()) {
				child = it.next();
				factory.writeTag(child, dos);
			}
		} else {
			dos.writeByte(1);
			dos.writeInt(0);
		}
	}

	@Override public Tag<Iterable<Tag<?>>> createTag(String tagName) {
		return new ListTag(this, tagName);
	}
	
	/*public final class Byte extends ListTagFactory<java.lang.Byte> {
		private Byte() {super((byte) 1);};
	};
	
	public final class Short extends ListTagFactory<java.lang.Short> {
		private Short() {super((byte) 2);};
	};
	
	public final class Integer extends ListTagFactory<java.lang.Integer> {
		private Integer() {super((byte) 3);};
	};
	
	public final class Long extends ListTagFactory<java.lang.Long> {
		private Long() {super((byte) 4);};
	};
	
	public final class Float extends ListTagFactory<java.lang.Float> {
		private Float() {super((byte) 5);};
	};
	
	public final class Double extends ListTagFactory<java.lang.Double> {
		private Double() {super((byte) 6);};
	};
	
	public final class ByteArray extends ListTagFactory<byte[]> {
		private ByteArray() {super((byte) 7);};
	};
	
	public final class String extends ListTagFactory<java.lang.String> {
		private String() {super((byte) 8);};
	};
	
	public final class List<R> extends ListTagFactory<Iterable<Tag<R>>> {
		private List() {super((byte) 9);};
	};
	
	public final class Compound extends ListTagFactory<Iterable<Tag<?>>> {
		private Compound() {super((byte) 10);};
	};
	
	public final class IntArray extends ListTagFactory<int[]> {
		private IntArray() {super((byte) 11);};
	};*/

}
